﻿using DevExpress.Utils.Taskbar.Core;
using DevExpress.Utils.Taskbar;
using DevExpress.WindowsMailClient.Win.Utils;
using DevExpress.XtraBars;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using System.IO;
using DevExpress.XtraBars.FluentDesignSystem;
using CamHKVision;
using DevExpress.Utils;
using DevExpress.Utils.Win;
using System.Threading.Tasks;
using FrameManager;
using GeneralLib;
using IOModule;
using DevExpress.XtraEditors;

namespace OPX_FlowGlueMachine
{
    public partial class FormMain : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
    {
        CamHKVision.CamHKVision camHKVision1;


        public FormMain()
        {

            TaskbarHelper.InitDemoJumpList(TaskbarAssistant.Default, this);
            AppProvider.MainForm = this;
            StartUpProcess.OnStart("OPX_FlowGlueMachine Start");
            InitializeComponent();
            
            StartUpProcess.OnRunning("Initializing...");
            InitModules();
            //for (int i = 0; i < 200; i++)
            //{
            //    System.Threading.Thread.Sleep(1);
            //    StartUpProcess.OnRunning("Loading..." + ((i + 1) * 100.0 / 200.0).ToString("0.0") + "%");
            //}
            StartUpProcess.OnRunning("Successfully loaded.");
            StartUpProcess.OnComplete();
           
            
        }
        public void InitModules()
        {
            StartUpProcess.OnRunning("InitModules...");
            FrameManager.FrameManager.Init();
            InitProjectModule();
            InitCamer();
            InitMotionCard();
            InitIOModule();
            InitTableModule();
            InitImageCalibModule();
            InitImageToolModule();
            InitGluePathModule();
            InitCustomModule();
            UserModule.UserManager.Init(barStaticItemLOG);
            StartUpProcess.OnRunning("Modules loaded.");
        }
        public void InitProjectModule()
        {
            StartUpProcess.OnRunning("InitProjectModule");
            ProjectModule.ProjectManager.Init();
            barStaticItemProjectName.Caption = ProjectModule.ProjectManager.ProjectSetting.ProjectName;
            StartUpProcess.OnRunning("ProjectModule loaded.");
        }
        public void InitCamer()
        {
            StartUpProcess.OnRunning("InitCameraModule");
            HalconDotNet.HOperatorSet.SetSystem("clip_region", new HalconDotNet.HTuple("false"));
            HalconDotNet.HOperatorSet.SetSystem("use_window_thread", "true");

            camHKVision1 = new CamHKVision.CamHKVision();
            camHKVision1.CreateActioner("Camera1");
            camHKVision1.actioner.InitCam("Camera1"); 
            FrameManager.FrameManager.Camera1 = camHKVision1.actioner;


            barStaticItemCamera.ItemAppearance.Normal.BackColor = FrameManager.FrameManager.Camera1.bInitOk ? Color.Green : Color.Red;
            StartUpProcess.OnRunning("CameraModule loaded.");



        }
        public void InitMotionCard()
        {
            StartUpProcess.OnRunning("InitCameraModule");
            ZMotion.ZMotionCard zMotionCard = new ZMotion.ZMotionCard();
            zMotionCard.Init("ZMotion");
            FrameManager.FrameManager.MotionCard = zMotionCard;
            barStaticItemMotionCard.ItemAppearance.Normal.BackColor = FrameManager.FrameManager.MotionCard.bInitOK ? Color.Green : Color.Red;
            StartUpProcess.OnRunning("CameraModule loaded.");
        }
        public void InitTableModule()
        {
            StartUpProcess.OnRunning("InitTableModule");
            TableModule.TableManager.Init();
            FrameManager.MachineStatus.Is4Axis = TableModule.TableManager.tableSystemSetting.tableSetting.tableAxisSettings[3].bUsed;
            GeneralDefine.GlueMachineSetting.Is4AxisMachine = TableModule.TableManager.tableSystemSetting.tableSetting.tableAxisSettings[3].bUsed;
            StartUpProcess.OnRunning("InitTableModule loaded.");
        }
        public void InitIOModule()
        {
            StartUpProcess.OnRunning("InitIOModule");
            IOModule.IOManager.Init();

            StartUpProcess.OnRunning("InitIOModule loaded.");
        }

        public void InitImageCalibModule()
        {
            StartUpProcess.OnRunning("InitImageCalibModule");
            ImageCalibModule.ImageCalibManager.Init();
            StartUpProcess.OnRunning("InitImageCalibModule loaded.");
        }
        public void InitImageToolModule()
        {
            StartUpProcess.OnRunning("InitImageToolModule");
            ImageTaskModule.ImageTaskManager.Init();
            StartUpProcess.OnRunning("InitImageToolModule loaded.");
        }
        public void InitGluePathModule()
        {
            StartUpProcess.OnRunning("InitGluePathModule");
            GluePathModule.GluePathManager.Init();

            StartUpProcess.OnRunning("InitGluePathModule loaded.");
        }

        public void InitCustomModule()
        {
            StartUpProcess.OnRunning("InitCustomModule");
            CustomModule.CustomManager.Init();

            StartUpProcess.OnRunning("InitCustomModule loaded.");
        }
        private void accordionControl1_ElementClick(object sender, DevExpress.XtraBars.Navigation.ElementClickEventArgs e)
        {
            //e.Element.
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            FrameManager.FrameManager.fluentDesignFormContainer1 = fluentDesignFormContainer1;

            if(FrameManager.MachineStatus.NoHomeAction)
                FrameManager.MachineStatus.bHomeed = true;

            ShowForm(CustomModule.CustomManager.OpenFrameStart());

            FrameManager.FrameManager.FrmMain = this;
            timerMachineStatus.Enabled = true;

            flyoutPanelMessageCenter.Options.AnchorType = PopupToolWindowAnchor.Center;
            FrameManager.FrameManager.flyoutPanelControl = flyoutPanelControlMessageCenter;
            FrameManager.FrameManager.flyoutPanel = flyoutPanelMessageCenter;
            FrameManager.FrameManager.flyoutPanelStack = stackPanelMessage;

            SetUseLevelVisible(UserModule.UserManager.iUserLevel);
        }
        public void SetUseLevelVisible(int iUserLevel)
        {
            if (iUserLevel == 0)
            {
                accordionControlElementEngineerUI.Visible = false;
                accordionControlDebug.Visible = false;
                accordionControlSetting.Visible = false;

            }
            if (iUserLevel == 1)
            {
                accordionControlElementEngineerUI.Visible = true;
                accordionControlDebug.Visible = false;
                accordionControlSetting.Visible= false;
            }
            if (iUserLevel == 2)
            {
                accordionControlElementEngineerUI.Visible = true;
                accordionControlDebug.Visible = true;
                accordionControlSetting.Visible = false;
            }
            if (iUserLevel > 2)
            {
                accordionControlElementEngineerUI.Visible = true;
                accordionControlDebug.Visible = true;
                accordionControlSetting.Visible = true;
            }
        }
        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            
            if (FrameManager.FrameManager.ExitingAppAction(LookAndFeel))
            {
                FrameManager.FrameManager.ProductSetting.Save();
                Program.skinSetting.UIStyle = skinDropDownButtonItem1.Caption;
                Program.skinSetting.UIPaletteName = skinPaletteDropDownButtonItem1.Caption;
                Program.skinSetting.Save();
                FrameManager.FrameManager.MotionCard.Close();
                ProjectModule.ProjectManager.ProjectSetting.Save();
            }
            else 
            {
                e.Cancel = true;
            }

        }

        private void barButtonItemSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            FrameManager.FrameManager.ProductSetting.Save();
            FrameManager.FrameManager.MotionCard.Save();
            ProjectModule.ProjectManager.ProjectSetting.Save();
            FrameManager.FrameManager.SaveProjectAction();
            camHKVision1.camGeneralSetting.Save();
            
        }

        private void barButtonItemOpen_ItemClick(object sender, ItemClickEventArgs e)
        {
            DialogResult dialogResult;
            ProjectModule.FormProjectSelect formProjectSelect = new ProjectModule.FormProjectSelect();
            dialogResult = formProjectSelect.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                ProjectModule.ProjectManager.ProjectSetting.ProjectName = formProjectSelect.strProjectName;
                ProjectModule.ProjectManager.ProjectSetting.Save();
                barStaticItemProjectName.Caption = ProjectModule.ProjectManager.ProjectSetting.ProjectName;
                FrameManager.FrameManager.OpenProjectAction();
            }
            
        }

        private void barButtonItemSaveAs_ItemClick(object sender, ItemClickEventArgs e)
        {
            string strBeforeProjectName = ProjectModule.ProjectManager.ProjectSetting.ProjectName;
            ProjectModule.FormProjectNameInput formProjectNameInput = new ProjectModule.FormProjectNameInput();
            formProjectNameInput.ShowDialog();
            if (formProjectNameInput.DialogResult != DialogResult.OK)
            {
                return;
            }
            ProjectModule.ProjectManager.ProjectSetting.ProjectName = formProjectNameInput.ProjectName;
            string srcdir = Application.StartupPath + @"\ProjectSetting\" + strBeforeProjectName + @"\";
            string desdir = Application.StartupPath + @"\ProjectSetting\" + ProjectModule.ProjectManager.ProjectSetting.ProjectName + @"\";


            CopyDirectory(srcdir, desdir);
            barStaticItemProjectName.Caption = ProjectModule.ProjectManager.ProjectSetting.ProjectName;
            ProjectModule.ProjectManager.ProjectSetting.Save();
            FrameManager.FrameManager.SaveAsProjectAction();
        }
        private static void CopyDirectory(string srcdir, string desdir)
        {
            string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1);
            string desfolderdir;
            if (folderName == "")
            {
                desfolderdir = desdir;
            }
            else
            {
                desfolderdir = desdir + "\\";
            }



            string[] filenames = Directory.GetFileSystemEntries(srcdir);
            foreach (string file in filenames)// 遍历所有的文件和目录 
            {

                if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 
                {
                    string currentdir = desfolderdir + file.Substring(file.LastIndexOf("\\") + 1);

                    if (!Directory.Exists(currentdir))
                    {

                        Directory.CreateDirectory(currentdir);

                    }
                    CopyDirectory(file, currentdir);
                }
                else // 否则直接copy文件 
                {

                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);
                    //srcfileName = desfolderdir + "\\" + srcfileName;
                    srcfileName = desfolderdir + srcfileName;
                    if (!Directory.Exists(desfolderdir))
                    {

                        Directory.CreateDirectory(desfolderdir);

                    }
                    //if (file.IndexOf(".txt") > 0)
                    //{

                    //}
                    //else
                    {
                        File.Copy(file, srcfileName, true);
                    }
                }

            }//foreach  

        }//function end

        private void accordionControlElementCameraSetting_Click(object sender, EventArgs e)
        {
            
            CamHKVision.XtraFormSetting frmSetting = new CamHKVision.XtraFormSetting();
            frmSetting.camGeneral = camHKVision1;
            frmSetting.strName = camHKVision1.strName;
            ShowForm(frmSetting);
            
        }
        public void ShowForm(Form form)
        {
            WaitForm1 waitForm1 = new WaitForm1();
            waitForm1.Show(this);
            waitForm1.Refresh();
            foreach (var item in fluentDesignFormContainer1.Controls)
            {
                if (item is Form)
                {
                    Form formItem = (Form)item;
                    formItem.Close();
                }
            }
            form.TopLevel = false;
            form.FormBorderStyle = FormBorderStyle.None;
            form.Size = fluentDesignFormContainer1.Size;
            form.Height = fluentDesignFormContainer1.Height-ribbonStatusBar1.Height;
            fluentDesignFormContainer1.Controls.Add(form);
            form.Show();
            waitForm1.Close();

        }

        private void fluentDesignFormContainer1_SizeChanged(object sender, EventArgs e)
        {
            foreach (var item in fluentDesignFormContainer1.Controls)
            {
                if (item is Form)
                {
                    Form formItem = (Form)item;
                    formItem.Size = fluentDesignFormContainer1.Size;
                    formItem.Height = fluentDesignFormContainer1.Height - ribbonStatusBar1.Height;
                }
            }
        }

        private void accordionControlElementMotionSetting_Click(object sender, EventArgs e)
        {
           
            Form frmSetting = FrameManager.FrameManager.MotionCard.ShowSettingForm();
            ShowForm(frmSetting);
           
        }

        private void accordionControlElementTableSetting_Click(object sender, EventArgs e)
        {
            
            Form frmSetting = TableModule.TableManager.OpenSettingForm();
            ShowForm(frmSetting);
            
        }

        private void accordionControlElement1_Click(object sender, EventArgs e)
        {
           
            Form frmSetting = TableModule.TableManager.OpenDedugForm();
            ShowForm(frmSetting);
            
        }

        private void accordionControlElementIOSetting_Click(object sender, EventArgs e)
        {
            
            Form frmSetting = IOModule.IOManager.OpenSettingForm();
            ShowForm(frmSetting);
            
        }

        private void accordionControlElementIODebug_Click(object sender, EventArgs e)
        {
           
            Form frmSetting = IOModule.IOManager.OpenDebugForm();
            ShowForm(frmSetting);
            
        }

        private void fluentDesignFormContainer1_Click(object sender, EventArgs e)
        {

        }

        private void timerMachineStatus_Tick(object sender, EventArgs e)
        {
            if (FrameManager.MachineStatus.bAlarm)
            {
                barButtonItemMachineStatus.ItemAppearance.Normal.BackColor = Color.Yellow;
            }
            else
            {
                if (FrameManager.MachineStatus.bStart)
                {
                    barButtonItemMachineStatus.ItemAppearance.Normal.BackColor = Color.Green;
                }
                else
                {
                    barButtonItemMachineStatus.ItemAppearance.Normal.BackColor = Color.Red;
                }
            }
            if (FrameManager.MachineStatus.bHomeed)
            {
                barButtonItemHomeOk.Enabled = true;
            }
            else
            {
                barButtonItemHomeOk.Enabled = false;
            }
            buttonEditTotal.Text = FrameManager.FrameManager.ProductSetting.Total.ToString();
            buttonEditInput.Text = FrameManager.FrameManager.ProductSetting.Input.ToString();
            buttonEditPass.Text = FrameManager.FrameManager.ProductSetting.Pass.ToString();
            buttonEditFail.Text = FrameManager.FrameManager.ProductSetting.Fail.ToString();
            buttonEditYeild.Text = ((double)FrameManager.FrameManager.ProductSetting.Pass/ (double)FrameManager.FrameManager.ProductSetting.Input).ToString("0.0");
            MachineStatusScaner.FreshMachineStatus();
        }
        
        private void accordionControlElementStartButton_Click(object sender, EventArgs e)
        {
            FrameManager.MachineStatus.SetMachineStartAction();
        }

        private void accordionControlElementStopButton_Click(object sender, EventArgs e)
        {
            FrameManager.MachineStatus.SetMachineStopAction();
        }

        private void simpleButtonStart_Click(object sender, EventArgs e)
        {
            FrameManager.MachineStatus.SetMachineStartAction();
        }

        private void simpleButtonStop_Click(object sender, EventArgs e)
        {
            FrameManager.MachineStatus.SetMachineStopAction();
        }

        private void simpleButtonReset_Click(object sender, EventArgs e)
        {
            FrameManager.MachineStatus.ResetMachineAlarmAction();
        }

        private void accordionControlHomePage_Click(object sender, EventArgs e)
        {
            if (FrameManager.FrameManager.FrmStart.Visible)
                return;
            ShowForm(CustomModule.CustomManager.OpenFrameStart());
        }

        private void accordionControlElementOrg_Click(object sender, EventArgs e)
        {
            //flyoutPanel1.OptionsBeakPanel.BeakLocation = BeakPanelBeakLocation.Bottom;

            flyoutPanel1.Options.AnchorType=PopupToolWindowAnchor.Right;
            if (flyoutPanel1.Visible == false)
                flyoutPanel1.ShowPopup(true);
            else
                flyoutPanel1.HidePopup(true);
            //if (flyoutPanel1.Visible == false)
            //    flyoutPanel1.ShowBeakForm(true);
            //else
            //    flyoutPanel1.HideBeakForm(true);
        }
        int iMessageCount = 0;
        private void simpleButtonAddAlarm_Click(object sender, EventArgs e)
        {
            iMessageCount++;
            MessageModule.MessageMagager.ShowAutoHideMessage("第"+iMessageCount.ToString("00")+"个测试");
        }

        private void simpleButtonAddAlarmMessage_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                MessageModule.MessageMagager.ShowDailogForm("报警测试");
            });
            
        }

        private void accordionControlElementImageTaskSetting_Click(object sender, EventArgs e)
        {
            Form frmSetting = ImageTaskModule.ImageTaskManager.OpenTaskCenterSettingForm();
            ShowForm(frmSetting);
        }

        private void accordionControlElementImageTaskEdit_Click(object sender, EventArgs e)
        {
            Form frmSetting = ImageTaskModule.ImageTaskManager.OpenTaskItemSettingForm();
            ShowForm(frmSetting);
        }

        private void accordionControlElementImageCalib_Click(object sender, EventArgs e)
        {
            ShowForm(ImageCalibModule.ImageCalibManager.OpenMainCalibSettingForm());
        }

        private void accordionControlImageCalibAction_Click(object sender, EventArgs e)
        {
            ShowForm(ImageCalibActionModule.CalibActionMagager.OpenActionModuleForm());
        }

        private void barButtonItemHomeReturn_ItemClick(object sender, ItemClickEventArgs e)
        {
            FrameManager.MachineStatus.SetHomeStartAction();
        }

        private void accordionControlElementGluePath_Click(object sender, EventArgs e)
        {
            double dZoffSet = TableModule.TableManager.tableRunner.GetPosition("产品离皮带高度").dZPos;
            ImageCalibModule.ImageCalibManager.ImageCalibHandeye.SetZOffSet(dZoffSet);
            ShowForm(GluePathModule.GluePathManager.ShowManagerForm());
        }

        private void buttonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Clear)
            {
                FrameManager.FrameManager.ProductSetting.Input=0;
                FrameManager.FrameManager.ProductSetting.Pass = 0;
                FrameManager.FrameManager.ProductSetting.Fail = 0;
            }
        }

        private void accordionControlElement3_Click(object sender, EventArgs e)
        {
            ShowForm(CustomModule.CustomManager.OpenEnginerForm());
           
        }

        private void accordionControlElement2_Click(object sender, EventArgs e)
        {
            ShowForm(CustomModule.CustomManager.OpenOperatorForm());
        }

        private void barButtonItemLogin_ItemClick(object sender, ItemClickEventArgs e)
        {
            UserModule.FormUserLogoIn formUserLogoIn = new UserModule.FormUserLogoIn();
            formUserLogoIn.ShowDialog();
        }

        private void barButtonItemMagager_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (UserModule.UserManager.iUserLevel > 2)
            {
                UserModule.FormUserManager formUserManager = new UserModule.FormUserManager();
                formUserManager.ShowDialog();
            }
            else
            {
                XtraMessageBox.Show("你需要管理的权限才能进入");
            }
        }
    }
}
